<script setup>
// 组件对外暴露一个 open 方法, 基于 open 传来的参数, 区分是添加还是编辑
// 1.open({}) => 表单无需渲染, 说明是添加
// 2.open({id, cate_name,...}) => 传来的参数是row, 说明是编辑, 需要回显
// 同时 调 open 也可以显示弹框
import { ref } from 'vue'
import { artAddChannelService, artEditChannelService } from '@/api/article.js'
const dialogVisible = ref(false)
const formRef = ref()
const emit = defineEmits(['success'])
// 表单校验
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}
// 提交 - 添加还是编辑 => 看 formModel 中有没有 id
const onSubmit = async () => {
  await formRef.value.validate()
  const isEdit = formModel.value.id
  // console.log(formModel.value)
  if (isEdit) {
    await artEditChannelService(formModel.value)
    ElMessage.success('编辑成功')
  } else {
    await artAddChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  // 通知 父组件进行回显
  emit('success')
}
const open = async (row) => {
  dialogVisible.value = true
  // console.log(row) // 测试传来的参数是空还是row,来判断是添加还是编辑
  formModel.value = { ...row } // 编辑需要回显, 所以拿到表单数据
  // console.log(formModel.value)
}
// 向外暴露
defineExpose({
  open
})
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <!-- 内容部分 -->
    <el-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      lable-width="100px"
      style="padding-right: 30px"
    >
      <el-form-item prop="cate_name" label="分类名称">
        <el-input
          v-model="formModel.cate_name"
          placeholder="请输入分类名称"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item prop="cate_alias" label="分类别名">
        <el-input
          v-model="formModel.cate_alias"
          placeholder="请输入分类别名"
          minlength="1"
          maxlength="15"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
